<template>
  <Modal v-model="open" :closeOnMask="false" hasDivider hasCloseIcon>
    <template #header>角色管理</template>
    <div>
      <Form :model="form" :rules="rules" mode="twocolumn" ref="form">
        <FormItem label="编码" prop="sn" required>
          <Input type="text" v-model="form.sn" :readonly="!isAdd"/>
        </FormItem>
        <FormItem label="角色名" prop="name">
          <Input type="text" v-model="form.name"/>
        </FormItem>
        <FormItem label="权限范围" prop="name">
          <Select v-model="form.scope" dict="DataScope" filterable></Select>
        </FormItem>
        <FormItem label="角色类型" prop="roleType">
          <Select v-model="form.roleType" dict="BranchType" filterable></Select>
        </FormItem>
      </Form>
    </div>
    <template #footer>
      <Button @click="open=false">取消</Button>
      <Button :loading="loading" color="primary" @click="saveOrUpdate">确认</Button>
    </template>
  </Modal>
</template>
<script>
import {DataSource, ajax, util} from 'framework'
import {message} from 'heyui'
export default {
  name: 'RoleDialog',
  emits:['change'],
  data: function () {
    return {
      open: false,
      loading: false,
      isAdd: false,
      form: {
        sn: null,
        name: null,
        roleType: null,
        scope:null,
      },
      //验证规则
      rules: {}
    }
  }, methods: {
    show(primary) {
      this.loading = true
      util.clean(this.form)
      if (primary) {//show edit
        this.isAdd = false
        ajax.get("role/detail", primary).then(r => {
          this.form = r.data
          this.loading = false;
          this.open = true;
        })
      } else {
        this.isAdd = true
        //show add

        this.open = true
        this.loading = false
      }
    },
    saveOrUpdate() {
      var validResult = this.$refs.form.valid();
      if (validResult.result) {
        this.loading = true
        ajax.post(this.isAdd ? 'role/add' : 'role/save', this.form).then(r => {
          this.open = false;
          message("已保存")
          this.$emit("change", r.data)
        }).catch(e => {
          this.loading = false
          message(r.message)
        })
      }
    }
  }
}
</script>
